﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace CURESendMail
{
    public partial class Form1 : Form
    {
        private string IsEMail;
        private string EMailTitle;	//邮件标题
        private string EMailAddress;//发件地址
        private string EMailCode;	//邮箱授权码
        private double EMailTime;	//发送邮件间隔时间（小时）
        private string EMailHost;	//邮箱服务地址
        private string EMailSendTime;//上次发送时间
        DateTime dtnext;
        string TimerInterval;//计时器时间间隔

        SendMail Smail = new SendMail();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            IsEMail = Smail.IsEMail();
            EMailTitle = Smail.GetParameter("EMailTitle");
            EMailAddress = Smail.GetParameter("EMailAddress");
            EMailCode = Smail.GetParameter("EMailCode");
            EMailTime = double.Parse(Smail.GetParameter("EMailTime"));
            EMailHost = Smail.GetParameter("EMailHost");
            EMailSendTime = Smail.GetParameter("EMailSendTime").Trim();
            TimerInterval = ConfigurationManager.AppSettings["TimerInterval"];

            string strnext = "";

            if (EMailSendTime.Length > 0)
            {
                dtnext = Convert.ToDateTime(EMailSendTime);
                dtnext = dtnext.AddHours(EMailTime);
                strnext = dtnext.ToString("yyyy-MM-dd HH:mm:ss");
            }

            this.textBox1.Text = EMailSendTime;
            this.textBox2.Text = EMailTime.ToString();
            this.textBox3.Text = strnext;

            timer1.Enabled = true;
            this.timer1.Interval = 10000;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            IsEMail = Smail.IsEMail();
            EMailTitle = Smail.GetParameter("EMailTitle");
            EMailAddress = Smail.GetParameter("EMailAddress");
            EMailCode = Smail.GetParameter("EMailCode");
            EMailTime = double.Parse(Smail.GetParameter("EMailTime"));
            EMailHost = Smail.GetParameter("EMailHost");
            EMailSendTime = Smail.GetParameter("EMailSendTime").Trim();
            string strnext = "";

            if (EMailSendTime.Length > 0)
            {
                dtnext = Convert.ToDateTime(EMailSendTime);
                dtnext = dtnext.AddHours(EMailTime);
                strnext = dtnext.ToString("yyyy-MM-dd HH:mm:ss");
            }

            this.textBox1.Text = EMailSendTime;
            this.textBox2.Text = EMailTime.ToString();
            this.textBox3.Text = strnext;

            if (IsEMail == "1")
            {               
                if (EMailSendTime == "" || EMailSendTime == null)
                {
                    SendAll();
                }
                else
                {

                    DateTime now = DateTime.Now;

                    if (DateTime.Compare(now, dtnext) > 0)
                    {
                        SendAll();
                    }
                }
            }          
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            SendAll(); //SendEmail("714382525@qq.com", "测试", "测试1213");
        }

        public void SendAll() 
        {
            List<string> list = Smail.GetUser();
            string start = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            string end = DateTime.Now.ToString("yyyy-MM-dd");
            string ls_txt = Smail.GetFid(start, end);

            int ll_count = list.Count;
            if (ll_count > 0)
            {
                for (int i = 0; i < ll_count; i++) 
                {
                    string[] str = list[i].Split(';');
                    string id = str[0];
                    string email = str[1];
                    this.SendEmail(email, EMailTitle, ls_txt);
                    Smail.InsertLog(id, email);
                }
                Smail.UpdateEMailSendTime();
            }


        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="Receiver">邮件接收人</param>
        /// <param name="Subject">邮件主题</param>
        /// <param name="content">邮件内容</param>    
        public void SendEmail(string Receiver, string Subject, string content)
        {
            System.Net.Mail.SmtpClient client = null;

            if (string.IsNullOrEmpty(Receiver) || string.IsNullOrEmpty(Subject)
                || string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException("SendEmail参数空异常！");
            }
            if (client == null)
            {
                try
                {
                    //163发送配置                    
                    client = new System.Net.Mail.SmtpClient();
                    client.Host = EMailHost;// "smtp.163.com";
                    client.Port = 25;
                    client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = true;


                    //qq发送配置的参数//切EnableSsl必须设置为true  
                    //client = new System.Net.Mail.SmtpClient();
                    //client.Host = "smtp.qq.com";
                    //client.Port = 25;
                    //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    //client.EnableSsl = true;
                    //client.UseDefaultCredentials = false;

                    client.Credentials = new System.Net.NetworkCredential(EMailAddress, EMailCode);//"BSWXBL@163.com", "bswxbl12345"
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            try
            {
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                Message.SubjectEncoding = System.Text.Encoding.UTF8;
                Message.BodyEncoding = System.Text.Encoding.UTF8;
                Message.Priority = System.Net.Mail.MailPriority.High;

                Message.From = new System.Net.Mail.MailAddress(EMailAddress);//"BSWXBL@163.com"
                //添加邮件接收人地址
                string[] receivers = Receiver.Split(new char[] { ',' });
                Array.ForEach(receivers.ToArray(), ToMail => { Message.To.Add(ToMail); });

                Message.Subject = Subject;
                Message.Body = content;
                Message.IsBodyHtml = true;
                client.Send(Message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void GetParameter() 
        {

        }

    }
}
